package org.ofbiz.wvtools.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javolution.util.FastList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.StringUtil;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.DelegatorFactory;
import org.ofbiz.entity.model.ModelEntity;
import org.ofbiz.entity.model.ModelField;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

public class CommonUtils {
    @SuppressWarnings("rawtypes")
    public static List splitStringToList(String inputString) {
	return splitCustomStringToList(inputString, ";");
    }

    @SuppressWarnings("rawtypes")
    public static List splitCustomStringToList(String inputString, String splitChar) {
	List result = FastList.newInstance();
	if (UtilValidate.isEmpty(inputString)) {
	    return result;
	}
	inputString = inputString.trim();
	String[] array = inputString.split(splitChar);
	for (int i = 0; i < array.length; i++) {
	    if (UtilValidate.isNotEmpty(array[i])) {
		result.add(array[i]);
	    }
	}
	return result;
    }

    public static Object wrapString(Object theString) {

	if (theString instanceof String) {
	    String s = (String) theString;
	    return StringUtil.wrapString(s);
	}
	return theString;
    }

    public static String replaceString(String str, String rep1, String rep2) {
	str = str.replaceAll("/online", "");
	str = str.substring(1, str.length());
	str = str.replaceAll(rep1, rep2);

	return str;
    }

    public static String sendPost(String url, String param) {
	OutputStreamWriter out = null;
	BufferedReader reader = null;
	String response = "";
	// 创建连接
	try {
	    URL httpUrl = null; // HTTP URL类 用这个类来创建连接
	    // 创建URL
	    httpUrl = new URL(url);
	    // 建立连接
	    HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
	    conn.setRequestMethod("POST");
	    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	    conn.setRequestProperty("connection", "keep-alive");
	    conn.setUseCaches(false);// 设置不要缓存
	    conn.setInstanceFollowRedirects(true);
	    conn.setDoOutput(true);
	    conn.setDoInput(true);
	    conn.connect();
	    // POST请求
	    out = new OutputStreamWriter(conn.getOutputStream());
	    out.write(param);
	    out.flush();
	    // 读取响应
	    reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
	    String lines;
	    while ((lines = reader.readLine()) != null) {
		lines = new String(lines.getBytes(), "utf-8");
		response += lines;
	    }
	    reader.close();
	    // 断开连接
	    conn.disconnect();

	} catch (Exception e) {
	    System.out.println("发送 POST 请求出现异常！" + e);
	    e.printStackTrace();
	}
	// 使用finally块来关闭输出流、输入流
	finally {
	    try {
		if (out != null) {
		    out.close();
		}
		if (reader != null) {
		    reader.close();
		}
	    } catch (IOException ex) {
		ex.printStackTrace();
	    }
	}
	return response;
    }

    // 获取一个时间差坐标
    public static List<String> getMonthList(String time1, String time2) {
	List<String> timeList = FastList.newInstance();
	try {
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");// 格式化为年月
	    Calendar min = Calendar.getInstance();
	    Calendar max = Calendar.getInstance();
	    min.setTime(sdf.parse(time1));
	    min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

	    max.setTime(sdf.parse(time2));
	    max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

	    Calendar curr = min;
	    while (curr.before(max)) {
	        timeList.add(sdf.format(curr.getTime()));
	        curr.add(Calendar.MONTH, 1);
	    }
	} catch (ParseException e) {
	    e.printStackTrace();
	}
	System.out.println(timeList);
	return timeList;
    }
    
    public static String getLastMonth() {
	Calendar cal = Calendar.getInstance();
	cal.add(Calendar.MONTH, -5);
	int year = cal.get(Calendar.YEAR);
	int month = cal.get(Calendar.MONTH )+1;
	System.out.println(month);
	String str = year + "-" + month;
	if(month<10) {
	    str = year + "-" + "0" + month;
	}
	
	return str;
    }
    public static Timestamp getLastYear(int year) {
	Calendar cal = Calendar.getInstance();
	cal.add(Calendar.YEAR, year);
	Timestamp time = new Timestamp(cal.getTimeInMillis());
	
	return time;
    }
    public static String getNowMonth() {
	Calendar cal = Calendar.getInstance();
	int year = cal.get(Calendar.YEAR);
	int month = cal.get(Calendar.MONTH )+1;
	String str = year + "-" + month;
	if(month<10) {
	    str = year + "-" +"0"+month;
	}
	
	return str;
    }
    /**
     * 获取一个本月开始和结束日期
     * 
     * @return
     */
    public static Map<String, Timestamp> getNowMonthDay(String time1) {
	Timestamp time = Timestamp.valueOf(time1 + "-01 00:00:00");
	Calendar ca = Calendar.getInstance();
	if (UtilValidate.isNotEmpty(time)) {
	    ca.setTime(time);
	}
	int maximum = ca.getActualMaximum(Calendar.DAY_OF_MONTH);
	int minmum = ca.getActualMinimum(Calendar.DAY_OF_MONTH);
	int day = ca.get(Calendar.DAY_OF_MONTH);
	Calendar cal = (Calendar) ca.clone();
	cal.add(Calendar.DATE, maximum - day);
	Date date2 = cal.getTime();
	cal = (Calendar) ca.clone();
	cal.add(Calendar.DATE, minmum - day);
	Date date1 = cal.getTime();
//	SimpleDateFormat f=new SimpleDateFormat("yyyy-MM-dd");
//	String strD=f.format(date1);
//	String strX=f.format(date2);
	Timestamp startDate = new Timestamp(date1.getTime());
	Timestamp endDate = new Timestamp(date2.getTime()+86399000);

	return UtilMisc.toMap("startDate", startDate, "endDate", endDate);
    }
    
    public static void main(String[] args) {
	//System.out.println(getMonthList("2021-10","2022-03"));
	System.out.println(getLastYear(-2));
	//System.out.println(getNowMonthDay("2021-10"));
    }
//    public static void main(String[] args) {
//    	
//    	Date date = new Date();
//    	Timestamp time =new Timestamp(date.getTime());
//    	System.out.println(time);
//    	System.out.println(getLastDay(time, new Long(-7)));
//    }

    @SuppressWarnings({ "unchecked" })
    public static Map<String, Object> readDataFromJsonMap(String fileName) {
	if (UtilValidate.isNotEmpty(fileName)) {
	    if (fileName.length() > 5) {
		String json = fileJson(fileName);
		// System.out.println(json);
		Map<String, Object> map = JSON.parseObject(json, Map.class);
		// System.out.println(map);
		List<Map<String, Object>> child = (List<Map<String, Object>>) map.get("child");
		System.out.println(child);
		return map;
	    } else {
		return null;
	    }
	} else {
	    return null;
	}
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static List<Map<String, Object>> readDataFromJsonList(String fileName) {
	String json = fileJson(fileName);
	System.out.println(json);
	List<Map<String, Object>> lists = FastList.newInstance();
	Gson gson = new Gson();
	JsonParser jsonParser = new JsonParser();
	System.out.println(json);
	JsonElement jsonElement = jsonParser.parse(json); // 将json字符串转换成JsonElement
	JsonArray jsonArray = jsonElement.getAsJsonArray(); // 将JsonElement转换成JsonArray
	Iterator it = jsonArray.iterator(); // Iterator处理
	while (it.hasNext()) { // 循环
	    jsonElement = (JsonElement) it.next(); // 提取JsonElement
	    json = jsonElement.toString(); // JsonElement转换成String
	    Map<String, Object> map = gson.fromJson(json, Map.class); // String转化成JavaBean
	    lists.add(map); // 加入List
	}
	return lists;
    }

    public static String fileJson(String fileName) {
	String str = "";
	// 1.生成httpclient，相当于该打开一个浏览器
	CloseableHttpClient httpClient = HttpClients.createDefault();
	CloseableHttpResponse response = null;
	// 2.创建get请求，相当于在浏览器地址栏输入 网址
	HttpGet request = new HttpGet(fileName);
	try {
	    // 3.执行get请求，相当于在输入地址栏后敲回车键
	    response = httpClient.execute(request);

	    // 4.判断响应状态为200，进行处理
	    System.out.println(response.getStatusLine().getStatusCode());
	    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
		// 5.获取响应内容
		HttpEntity httpEntity = response.getEntity();
		str = EntityUtils.toString(httpEntity, "utf-8");
	    } else {
		// 如果返回状态不是200，比如404（页面不存在）等，根据情况做处理，这里略
		System.out.println("返回状态不是200");
	    }
	} catch (ClientProtocolException e) {
	    e.printStackTrace();
	} catch (IOException e) {
	    e.printStackTrace();
	} finally {
	    // 6.关闭
	    HttpClientUtils.closeQuietly(response);
	    HttpClientUtils.closeQuietly(httpClient);
	}
	return str;
    }

    public static boolean isEquals(List<String> list1, List<String> list2) {
	if (null != list1 && null != list2) {
	    if (list1.containsAll(list2) && list2.containsAll(list1)) {
		return true;
	    }
	    return false;
	}
	return true;
    }

}
